import { format, getTime } from 'date-fns'

const DATE_TIME_FORMAT = 'yyyy-MM-dd HH:mm'
const DATE_FORMAT = 'yyyy-MM-dd'

export function formatToDateTime(date: Date | number, formatStr = DATE_TIME_FORMAT): string {
  return format(date, formatStr)
}

export function formatToDate(date: Date | number, formatStr = DATE_FORMAT): string {
  return format(date, formatStr)
}

export function formatToDateMonth(date: Date | number): string {
  return format(date, 'yyyy-MM')
}

export function formatDaterangeToDate(
  daterange: [number, number] | undefined,
  formatStr = DATE_FORMAT,
): { startDate: string | undefined; endDate: string | undefined } {
  const [startDate, endDate] = daterange || []

  if (!startDate || !endDate) {
    return { startDate: undefined, endDate: undefined }
  }

  return {
    startDate: formatToDate(startDate, formatStr),
    endDate: formatToDate(endDate, formatStr),
  }
}

/**
 * @author zxyue25
 * @desc 获取当前时间或者某个时间的毫秒级时间戳；
 * 如果入参是秒级时间戳（10位）, 则乘以1000返回毫秒级（13位）时间戳；主要场景在server返回了秒级时间戳, 前端先乘以1000转换成日期展示
 * @param date - Date | Number
 * @returns 返回格式化后的毫秒级时间戳 - Number
 */
export const getMilliTimestamp = (date?: number | Date): number => {
  if (!date) {
    return getTime(new Date())
  } else {
    if (date instanceof Date) {
      return getTime(date)
    } else {
      if (date.toString().length === 10) {
        return getTime(date * 1000)
      } else {
        return date
      }
    }
  }
}

/**
 * 计算相差天数
 * @param params
 *    timeType: 1:上午; 2:下午
 * @returns
 */
export function computedDays(params: {
  startTime: Date
  startTimeType: number
  endTime: Date
  endTimeType: number
}): number {
  const { startTime, startTimeType, endTime, endTimeType } = params

  let right = startTimeType === endTimeType ? 0.5 : 1
  if (startTimeType > endTimeType) {
    right = 0
  }

  const diff = endTime.getTime() - startTime.getTime()
  return Math.floor(diff / (24 * 60 * 60 * 1000)) + right
}
